package team.fourth.combat.security;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import team.fourth.combat.pojo.Permission;
import team.fourth.combat.pojo.Role;
import team.fourth.combat.pojo.User;
import team.fourth.combat.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 首先要让spring知道MySecurityUserService帮我们创建对象
 *          1、使用Bean标签
 *                    <bean class="com.itheima.security.MySecurityUserService" id="mySecurityUserService"></bean>
 *          2、加注解 + 包扫描
 *             @Component
 *             <context:component-scan base-package="com.itheima.security"></context:component-scan>
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {


    @Reference
    UserService userService;

    /**
     * 根据用户名查询用户信息（用户名，密码，用户的权限，用户的角色）
     * @param username 就是我们在登录页面输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         //调用userService的Dubbo服务根据用户名查询用户信息（密码，用户的权限集合）
         User user =  userService.loadUserByUsername(username);//返回一个User对象，User对象里面有密码，还有一个用户的角色集合，角色对象里面有一个存储角色对应权限集合的参数（和套餐，检查组，检查项结构类似）
         if(null == user){
             return null;
         }

         //可以一个sql查询出用户的权限集合,留给大家练习一下，提示3表联合查询

         List<SimpleGrantedAuthority> authorities = new ArrayList<>();//把用户所有的权限keyword放到这个集合里面
         Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                Set<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }

        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
